async function fetchData() {
  try {
    const response = await fetch("https://randomuser.me/api?results=50");
    const data = await response.json();
    console.log(data.results);
    return data.results;
  } catch (error) {
    console.error("Error:", error);
  }
}
let result = [];
let searchList = [];
let ul = document.querySelector("ul");
let lis = [];
async function init() {
  result = await fetchData();
  result.forEach((peo) => {
    let name = peo.name.first + " " + peo.name.last;
    let loc = peo.location.city + ", " + peo.location.country;
    let imgUrl = peo.picture.large;
    createLi(name, loc, imgUrl);
  });
}

// init();

let search = document.querySelector("input");
search.addEventListener("input", () => {
  ul.innerHTML = "";
  if (search.value === "") {
    lis.forEach((li, idx) => {
      ul.appendChild(li);
    });
  } else {
    let key = search.value;

    lis.forEach((li, idx) => {
      if (searchList[idx].includes(key)) {
        ul.appendChild(li);
      }
    });
  }
});

function createLi(name, loc, imgUrl) {
  let newLi = document.createElement("li");
  let newLeft = document.createElement("div");
  let newRight = document.createElement("div");
  let newImg = document.createElement("img");
  let newName = document.createElement("div");
  let newLoc = document.createElement("div");
  newLeft.classList.add("left");
  newRight.classList.add("right");
  newName.classList.add("name");
  newLoc.classList.add("loc");
  newImg.src = imgUrl;
  newName.textContent = name;
  newLoc.textContent = loc;
  newLi.appendChild(newLeft);
  newLi.appendChild(newRight);
  newLeft.appendChild(newImg);
  newRight.appendChild(newName);
  newRight.appendChild(newLoc);
  ul.appendChild(newLi);
  lis.push(newLi);
  searchList.push(name + loc + imgUrl);
}
